package com.manfred.ex01.other;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class TestSocket {
	public static void main(String[] args) throws Exception {
		Socket socket = new Socket("www.baidu.com", 80);
		OutputStream outStream = socket.getOutputStream();
		PrintWriter out = new PrintWriter(outStream, true);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));

		// send an HTTP request to the web server
		out.println("GET / HTTP/1.1");
		out.println("Host: www.baidu.com");
		out.println("Connection: close");
		out.println();

		// read the response
		boolean loop = true;
		StringBuffer sb = new StringBuffer(8096);
		while (loop) {
			if (in.ready()) {
				int i = 0;
				while (-1 != i) {
					i = in.read();
					sb.append((char) i);
				}
				loop = false;
			}
			TimeUnit.MILLISECONDS.sleep(50);
		}

		// display the response to the out console
		System.out.println(sb.toString());
		socket.close();
	}
}
